package com.redis.lock;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @date 2020-09-22 下午4:51
 */
public class RedisWithReentrantLock {
    private final ThreadLocal<Map<String, Integer>> lockers = new ThreadLocal<>();

    private final Jedis jedis;

    public RedisWithReentrantLock(Jedis jedis) {
        this.jedis = jedis;
    }

    /**
     * Lock boolean.
     *
     * @param key the key
     * @return the boolean
     */
    private boolean _lock(String key) {
        final String set = jedis.set(key, "", SetParams.setParams().ex(5).nx());
        return Objects.nonNull(set);
    }

    /**
     * Unlock.
     *
     * @param key the key
     */
    private void _unlock(String key) {
        jedis.del(key);
    }

    private Map<String, Integer> currentLockers() {
        final Map<String, Integer> refs = lockers.get();
        if (Objects.nonNull(refs)) {
            return refs;
        }
        lockers.set(new HashMap<>());
        return lockers.get();
    }

    /**
     * Lock boolean.
     *
     * @param key the key
     * @return the boolean
     */
    public boolean lock(String key) {
        final Map<String, Integer> refs = currentLockers();
        final Integer refCnt = refs.get(key);
        if (Objects.nonNull(refCnt)) {
            refs.put(key, refCnt + 1);
            return true;
        }
        final boolean ok = this._lock(key);
        if (!ok) {
            return false;
        }
        refs.put(key, 1);
        return true;
    }

    /**
     * Unlock boolean.
     *
     * @param key the key
     * @return the boolean
     */
    public boolean unlock(String key) {
        Map<String, Integer> refs = currentLockers();
        Integer refCnt = refs.get(key);
        if (Objects.isNull(refCnt)) {
            return false;
        }
        refCnt -= 1;
        if (refCnt > 0) {
            refs.put(key, refCnt);
        } else {
            refs.remove(key);
            this._unlock(key);
        }
        return true;
    }
}
